package com.start.manager.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.start.manager.dao.MenuDao;
import com.start.manager.domain.common.MenuAll;
import com.start.manager.domain.entity.Menu;
import com.start.manager.service.IMenuService;
import com.start.manager.util.constant.RedisConstant;
import com.jienlee.common.redis.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Lijian
 * @since 2019-12-26
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuDao, Menu> implements IMenuService {


    @Override
    public List<MenuAll> findByRedisList() {
        String value = RedisUtil.get(RedisConstant.baseName, RedisConstant.RedisKeyConstant.MENU, String.class);
        if (StringUtils.isNotBlank(value)) {
            JSONArray objects = JSONArray.parseArray(value);
            List<MenuAll> menuAlls = objects.toJavaList(MenuAll.class);
            return menuAlls;
        }
        //数据库中查询
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("parent_id");
        queryWrapper.orderByAsc("menu_sort");
        List<Menu> menus = this.baseMapper.selectList(queryWrapper);
        List<MenuAll> list = new ArrayList<>();
        for (Menu menu : menus) {
            MenuAll menuAll = new MenuAll();
            BeanUtils.copyProperties(menu, menuAll);
            QueryWrapper<Menu> queryWrapperChild = new QueryWrapper<>();
            queryWrapperChild.eq("parent_id", menuAll.getId());
            queryWrapperChild.orderByAsc("menu_sort");
            menuAll.setChildren(this.baseMapper.selectList(queryWrapperChild));
            list.add(menuAll);
        }
        RedisUtil.set(RedisConstant.baseName, RedisConstant.RedisKeyConstant.MENU, list);
        return list;
    }
}
